package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.config.ConditionColumn;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成查询条件
 * @author guobingbing
 * @create 2023/6/9 22:40
 */
public class QueryConditionsGenerator extends AbstractXmlElementGenerator {

	public QueryConditionsGenerator(){
		super();
	}

	@Override
	public void addElements(XmlElement parentElement) {
		XmlElement answer = new XmlElement("sql"); //$NON-NLS-1$

		answer.addAttribute(new Attribute("id", introspectedTable.getQueryConditionsId())); //$NON-NLS-1$

		XmlElement where = new XmlElement("where");
		answer.addElement(where);

		ConditionColumn conditionColumn = introspectedTable.getTableConfiguration().getConditionColumn();
		if(conditionColumn!=null){
			List<IntrospectedColumn> columns = ListUtilities.removeGeneratedAlwaysColumns(introspectedTable.getNonPrimaryKeyColumns());
			Map<String, IntrospectedColumn> columnMap = new HashMap<>();
			for(IntrospectedColumn col : columns){
				columnMap.put(col.getActualColumnName(), col);
			}

			StringBuilder sb = new StringBuilder();
			List<String> cols = conditionColumn.getColumns();
			for(String col : cols){
				sb.setLength(0);
				IntrospectedColumn column = columnMap.get(col);

				sb.append(column.getJavaProperty());
				sb.append(" != null ");
				if("varchar".equalsIgnoreCase(column.getJdbcTypeName()) ||
						"char".equalsIgnoreCase(column.getJdbcTypeName())){
					sb.append("and ").append(column.getJavaProperty()).append(" != ''");
				}
				XmlElement conditionElement = new XmlElement("if");
				conditionElement.addAttribute(new Attribute("test", sb.toString()));
				where.addElement(conditionElement);

				sb.setLength(0);
				sb.append("and ");
				sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(column));
				sb.append(" = "); //$NON-NLS-1$
				sb.append(MyBatis3FormattingUtilities.getParameterClause(column));

				conditionElement.addElement(new TextElement(sb.toString()));
			}
		}

		context.getCommentGenerator().addComment(answer);

		if (context.getPlugins().sqlMapBaseColumnListElementGenerated(answer, introspectedTable)) {
			parentElement.addElement(answer);
		}
	}
}
